package com.quanyan.alipay.util;

import com.quanyan.alipay.config.AlipayConfig;
import com.quanyan.common.encrypt.Coder;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by zijun.song on 2015/10/6.
 */
public class AliPayOrderQuery {

    private static Logger logger = LoggerFactory.getLogger(AliPayOrderQuery.class);

    /**
     * @param orderNo 系统订单号
     * @param tsn     支付宝订单号
     * @return
     */
    public static Map<String, String> query(String orderNo, String tsn, AlipayConfig alipayConfig) {
        Map<String, String> sParaTemp = new HashMap<String, String>();
        sParaTemp.put("service", "single_trade_query");
        sParaTemp.put("partner", alipayConfig.getPartner());
        sParaTemp.put("_input_charset", alipayConfig.getInput_charset());
        if (!StringUtils.isEmpty(tsn)) {
            sParaTemp.put("trade_no", tsn);
        }
        if (!StringUtils.isEmpty(orderNo)) {
            sParaTemp.put("out_trade_no", orderNo);
        }
        //建立请求
        String sHtmlText = null;
        try {
            sHtmlText = AlipaySubmit.buildRequest("", "", sParaTemp, alipayConfig,AlipaySubmit.ALIPAY_GATEWAY_NEW, Coder.KEY_MD5);
            Map<String, String> result = convertXmlToMap(sHtmlText);
            Map<String, String> aliResult = new HashMap<String, String>();
            if (result.get("is_success").equals("T")) { //请求成功.
                aliResult.put("status", "SUCCESS");
                aliResult.put("trade_status", result.get("trade_status"));
                aliResult.put("trade_no", result.get("trade_no"));
                aliResult.put("out_trade_no", result.get("out_trade_no"));
                aliResult.put("refund_status", result.get("refund_status"));
            } else {//请求失败.
                aliResult.put("msg", result.get("error"));
                aliResult.put("status", "FAIL");
            }

            return aliResult;
        } catch (Exception e) {
            logger.warn(sHtmlText);
            logger.error(getFullStackTraceToString(e));
        }
        return null;
    }


    public static void parse(Map<String, String> map) {

    }


    private static String getFullStackTraceToString(Exception exception) {
        StringWriter stringWriter = new StringWriter();
        exception.printStackTrace(new PrintWriter(stringWriter, true));
        return stringWriter.toString();
    }


    /**
     * xml to map xml <node><key label="key1">value1</key><key
     * label="key2">value2</key>......</node>
     *
     * @param xml
     * @return
     */
    private static Map<String, String> convertXmlToMap(String xml) {
        if (xml == null) {
            return null;
        }
        try {
            Map<String, String> map = new HashMap<String, String>();
            Document document = DocumentHelper.parseText(xml);
            Element nodeElement = document.getRootElement();
            List node = nodeElement.elements();
            for (Iterator it = node.iterator(); it.hasNext(); ) {
                Element elm = (Element) it.next();
                if (elm.attributeValue("label") == null) {
                    map.put(elm.getQualifiedName(), elm.getText());
                } else {
                    map.put(elm.attributeValue("label"), elm.getText());
                }
            }
            return map;
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return null;
    }
}
